package Graph.Medium;

import java.util.LinkedList;
import java.util.Queue;

public class LC0994 {
    public int orangesRotting(int[][] grid) {
        Queue<int[]> queue = new LinkedList<>();
        int M = grid.length, N = grid[0].length;
        int nNodesThisLevel = 0, nNodesNextLevel = 0;
        int minute = 0;
        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                if (grid[i][j] == 2) {
                    queue.offer(new int[]{i, j});
                    nNodesThisLevel++;
                }
            }
        }

        int[][] deltas = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        while (!queue.isEmpty()) {
            int[] pos = queue.poll();
            nNodesThisLevel--;

            for (int[] delta : deltas) {
                int x = pos[0] + delta[0];
                int y = pos[1] + delta[1];
                if (x >= 0 && x < M && y >= 0 && y < N && grid[x][y] == 1) {
                    grid[x][y] = 2;
                    queue.offer(new int[]{x, y});
                    nNodesNextLevel++;
                }
            }

            if (nNodesThisLevel == 0) {
                if (nNodesNextLevel > 0) {
                    minute++;
                    nNodesThisLevel = nNodesNextLevel;
                    nNodesNextLevel = 0;
                } else break;
            }
        }

        for (int i = 0; i < M; i++) {
            for (int j = 0; j < N; j++) {
                if (grid[i][j] == 1) return -1;
            }
        }
        return minute;
    }

    public static void main(String[] args) {
        int[][] grid = new int[][]{
                {2, 1, 1},
                {1, 1, 0},
                {0, 1, 1}
        };
        LC0994 solver = new LC0994();
        solver.orangesRotting(grid);
    }
}
